

/**
 * 通用js方法封装处理
 * Copyright (c) 2019 devdiv
 */

/**
 * 日期格式化
 * @param {*} time 
 * @param {*} pattern 
 * @returns 
 */
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

/**
 * 表单重置
 * @param {*} refName 
 */
export function resetForm(refName) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields();
  }
}

/**
 * 添加日期范围
 * @param {*} params 
 * @param {*} dateRange 
 * @param {*} propName 
 * @returns 
 */
export function addDateRange(params, dateRange, propName) {
  let search = params;
  dateRange = Array.isArray(dateRange) ? dateRange : [];
  if (typeof (propName) === 'undefined') {
    search['start_time'] = dateRange[0];
    search['end_time'] = dateRange[1];
  } else {
    search['start' + propName] = dateRange[0];
    search['end' + propName] = dateRange[1];
  }
  return search;
}

/**
 * 回显数据字典
 * @param {*} datas 
 * @param {*} value 
 * @returns 
 */
export function selectDictLabel(datas, value) {
  if (value === undefined) {
    return "";
  }
  var actions = [];
  Object.keys(datas).some((key) => {
    if (datas[key].value == ('' + value)) {
      actions.push(datas[key].label);
      return true;
    }
  })
  if (actions.length === 0) {
    actions.push(value);
  }
  return actions.join('');
}

/**
 * 回显数据字典（字符串数组）
 * @param {*} datas 
 * @param {*} value 
 * @param {*} separator 
 * @returns 
 */
export function selectDictLabels(datas, value, separator) {
  if (value === undefined || value.length === 0) {
    return "";
  }
  if (Array.isArray(value)) {
    value = value.join(",");
  }
  var actions = [];
  var currentSeparator = undefined === separator ? "," : separator;
  var temp = value.split(currentSeparator);
  Object.keys(value.split(currentSeparator)).some((val) => {
    var match = false;
    Object.keys(datas).some((key) => {
      if (datas[key].value == ('' + temp[val])) {
        actions.push(datas[key].label + currentSeparator);
        match = true;
      }
    })
    if (!match) {
      actions.push(temp[val] + currentSeparator);
    }
  })
  return actions.join('').substring(0, actions.join('').length - 1);
}

/**
 * 字符串格式化(%s )
 * @param {*} str 
 * @returns 
 */
export function sprintf(str) {
  var args = arguments, flag = true, i = 1;
  str = str.replace(/%s/g, function () {
    var arg = args[i++];
    if (typeof arg === 'undefined') {
      flag = false;
      return '';
    }
    return arg;
  });
  return flag ? str : '';
}

/**
 * 转换字符串，undefined,null等转化为""
 * @param {*} str 
 * @returns 
 */
export function parseStrEmpty(str) {
  if (!str || str == "undefined" || str == "null") {
    return "";
  }
  return str;
}

/**
 * 数据合并
 * @param {*} source 
 * @param {*} target 
 * @returns 
 */
export function mergeRecursive(source, target) {
  for (var p in target) {
    try {
      if (target[p].constructor == Object) {
        source[p] = mergeRecursive(source[p], target[p]);
      } else {
        source[p] = target[p];
      }
    } catch (e) {
      source[p] = target[p];
    }
  }
  return source;
};

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parent 父节点字段 默认 'parent'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parent, children) {
  let config = {
    id: id || 'id',
    parent: parent || 'parent',
    childrenList: children || 'children'
  };

  var childrenListMap = {};
  var nodeIds = {};
  var tree = [];

  for (let d of data) {
    let parent = d[config.parent];
    if (childrenListMap[parent] == null) {
      childrenListMap[parent] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parent].push(d);
  }

  for (let d of data) {
    let parent = d[config.parent];
    if (nodeIds[parent] == null) {
      tree.push(d);
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }
  return tree;
}

/**
* 参数处理
* @param {*} params  参数
*/
export function tansParams(params) {
  let result = ''
  for (const [key, value] of Object.entries(params)) {
    var part = encodeURIComponent(key) + "=";
    if (value !== null && value !== "" && typeof (value) !== "undefined") {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
            let params = key + '[' + key + ']';
            var subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result
}

/**
* Download参数处理
* @param {*} params  参数
*/
export function tansDownloadParams(params) {
  if (Object.keys(params).length === 0) {
    // 当 params 为空对象时，根据需要进行处理
    return null;
  }

  let formData = new FormData();
  for (const [key, value] of Object.entries(params)) {
    formData.append(key, value);
  }
  return formData;
}

/**
 * 返回项目路径
 * @param {*} p 
 * @returns 
 */
export function getNormalPath(p) {
  if (p.length === 0 || !p || p == 'undefined') {
    return p
  };
  let res = p.replace('//', '/')
  if (res[res.length - 1] === '/') {
    return res.slice(0, res.length - 1)
  }
  return res;
}

/**
 * 验证是否为blob格式
 * @param {*} data 
 * @returns 
 */
export async function blobValidate(data) {
  return data.type !== 'application/json'
}

/**
 * 初始化Select对象为可见字符
 * @param {*} x 
 * @param {*} y 
 * @param {*} t 
 * @returns 
 */
export function initOptions(x, y, t = "name") {
  let r = []
  if (x) {
    r = [{}];
    r[0]["id"] = x;
    r[0][t] = y;
  }
  return r;
}

/**
 * 由对象获取对象UUID信息
 * @param {*} items 
 * @returns 
 */
export function formatOptions(items) {
  return items.map(function (item) { return typeof (item) === "object" ? item.value : item })
}

/**
 * 穿梭框数据生成器
 * @param {*} tableSchema 
 * @returns Object
 */
export function genTransferData(tableSchema) {
  let tdata = []
  tableSchema.map((item, index) => {
    if ('visible' in item) {
      let obj = {}
      obj.key = index
      obj.label = item.label
      obj.visible = item.visible
      tdata.push(obj)
    }
  })
  return tdata
}

/**
 * 驼峰命名与短横线命名的转换
 * @param {驼峰命名} str 
 * @returns 
 */
export function getKebabCase(str) {
  return str.replace(/A-Z/g, function (item) {
    return '-' + item.toLowerCase()
  })
}

/**
 * 驼峰命名与短横线命名的转换
 * @param {短横线命名} str 
 * @returns 
 */
export function getCamelCase(str) {
  return str.replace(/-([a-z])/g, function (keb, item) {
    return item.toUpperCase()
  })
}

/**
 * 定时刷新数据，间隔3秒
 */
let nIntervId;
export function startRefresh(func) {
  if (!nIntervId) {
    nIntervId = setInterval(func, 3000)
  }
}

/**
 * 取消定时刷新数据
 */

export function stopRefresh() {
  clearInterval(nIntervId);
  nIntervId = null;
}

/**
 * 将接口数据转换为所需的格式
 * 例如：[
  {"create_time": "2024-05-24", "count": 1},
  {"create_time": "2023-06-07", "count": 1}
  ]
 * @param {*} data 
 * @returns 
 */
export function countDataByCreateTime(data) {
  const counts = {};

  // 遍历每条记录，提取日期部分，并计数
  data.forEach(item => {
    // 提取日期部分（假设create_time总是有效且格式正确）
    const date = item.create_time.split(' ')[0];

    // 如果该日期已存在于counts对象中，则增加其计数，否则初始化为1
    if (counts[date]) {
      counts[date]++;
    } else {
      counts[date] = 1;
    }
  });

  // 将counts对象转换为数组
  const result = [];
  for (const [date, count] of Object.entries(counts)) {
    result.push({ create_time: date, count: count });
  }

  return result;
}

/**
 * 根据当前节点收集所有节点的ID
 * @param {*} data 
 * @returns 
 */
export function extractNodeIds(data) {
  let result = [];
  function traverse(node) {
    // 仅提取当前节点的id  
    result.push(node.id);
    // 递归遍历子节点  
    if (node.children && node.children.length > 0) {
      node.children.forEach(child => traverse(child));
    }
  }
  // 从根节点开始遍历  
  traverse(data);
  return result;
}